# -*- coding:utf-8 -*-
from PySide6.QtWidgets import (QMenuBar, QMenu, QGroupBox, QHBoxLayout)
from PySide6.QtGui import (QAction, QActionGroup)
from PySide6.QtCore import Signal

class MenuGroup(QGroupBox):
    """
    自定义菜单栏组件
    """
    language_changed = Signal(str)  # 语言切换信号
    
    def __init__(self, language_dict, parent=None):
        super().__init__(parent)
        self.language_dict = language_dict
        self.language_actions = {}
        
        # 隐藏边框，因为菜单栏通常不需要边框
        self.setStyleSheet("border: none;")
        
        # 水平布局
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建菜单栏
        self.menu_bar = QMenuBar(self)
        layout.addWidget(self.menu_bar)
        
        # 初始化菜单
        self.init_menus()
    
    def init_menus(self):
        """初始化菜单"""
        # 语言菜单
        self.language_menu = QMenu(self)
        self.menu_bar.addMenu(self.language_menu)
        
        # 语言动作组
        self.language_action_group = QActionGroup(self)
        self.language_action_group.setExclusive(True)
        
        # 为每种语言创建菜单项
        for lang_code, lang_data in self.language_dict.items():
            action = QAction(lang_data.get("lang_name", lang_code), self)
            action.setCheckable(True)
            action.setData(lang_code)
            self.language_action_group.addAction(action)
            self.language_menu.addAction(action)
            self.language_actions[lang_code] = action
        
        # 帮助菜单
        self.help_menu = QMenu(self)
        self.menu_bar.addMenu(self.help_menu)
        
        # 关于动作
        self.about_action = QAction(self)
        self.help_menu.addAction(self.about_action)
        
        self.language_menu.setTitle("Language")
        self.help_menu.setTitle("Help")
        self.about_action.setText("About")
        # 连接语言切换信号
        self.language_action_group.triggered.connect(self.handle_language_change)
    
    def set_language(self, lang_data):
        """设置菜单语言"""
        # 更新菜单文本
        self.language_menu.setTitle(lang_data.get("menu_language", "Language"))
        self.help_menu.setTitle(lang_data.get("menu_help", "Help"))
        self.about_action.setText(lang_data.get("action_about", "About"))
        
        # 更新语言选项文本
        for lang_code, action in self.language_actions.items():
            if lang_code in self.language_dict:
                lang_name = self.language_dict[lang_code].get("lang_name", lang_code)
                action.setText(lang_name)
    
    def handle_language_change(self, action):
        """处理语言切换事件"""
        lang_code = action.data()
        self.language_changed.emit(lang_code)
    
    def bind_about_action(self, handler):
        """绑定关于动作"""
        self.about_action.triggered.connect(handler)
    
    def set_current_language(self, lang_code):
        """设置当前选中的语言"""
        if lang_code in self.language_actions:
            self.language_actions[lang_code].setChecked(True)